package org.peppa;

import com.fazecast.jSerialComm.SerialPort;
import org.peppa.utils.ModBusCommandUtil;

import java.util.Arrays;

import static org.peppa.utils.ModBusCommandUtil.intToByte;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
    // 电机启动指令
    public static final byte[] START_MOTOR = new byte[]{0x05, 0x06, 0x00, 0x02, 0x00, 0x01, intToByte(0xE8)[1], 0x4E};

    // 电机正转（向前运动）指令
    public static final byte[] FORWARD_MOTOR = new byte[]{0x05, 0x06, 0x00, 0x01, 0x00, 0x00, intToByte(0xD9)[0], intToByte(0xD9)[1], intToByte(0x8E)[0], intToByte(0x8E)[1]};

    // 电机反转（向后运动/复位）指令
    public static final byte[] REVERSE_MOTOR = new byte[]{0x05, 0x06, 0x00, 0x01, 0x00, 0x01, 0x18, 0x4E};

    // 查询电机运行状态指令
    public static final byte[] QUERY_MOTOR_STATUS = new byte[]{0x05, 0x03, 0x00, 0x02, 0x00, 0x01, 0x24, 0x4E};

    // 未运行时下位机回复
    public static final byte[] MOTOR_STOPPED_RESPONSE = new byte[]{0x05, 0x03, 0x02, 0x00, 0x00, 0x49,intToByte(0x84)[0], intToByte(0x84)[1] };

    // 运行时下位机回复
    public static final byte[] MOTOR_RUNNING_RESPONSE = new byte[]{0x05, 0x03, 0x02, 0x00, 0x01, intToByte(0x88)[0], intToByte(0x88)[1], 0x44};

    // 1号光幕读取指令
    public static final byte[] READ_PHOTOCURTAIN_1 = new byte[]{0x01, 0x03, 0x00,intToByte(0x9F)[0], intToByte(0x9F)[1] , 0x00, 0x01, intToByte(0xB4)[0], intToByte(0xB4)[1], 0x24};

    // 2号光幕读取指令
    public static final byte[] READ_PHOTOCURTAIN_2 = new byte[]{0x02, 0x03, 0x00, intToByte(0x9F)[0], intToByte(0x9F)[1], 0x00, 0x01,intToByte(0xB4)[0], intToByte(0xB4)[1] , 0x17};

    public static final byte[] STOP_MOTOR = new byte[]{0x04, 0x06, 0x00, 0x03, 0x00, 0x01, 0xB};
    public static void main(String[] args) {
        SerialPort serialPort = ModBusCommandUtil.openPort("COM1", 115200, 8, 1, 0);
        // 电机启动指令
        ModBusCommandUtil.sendWriteCommand(serialPort,START_MOTOR);
        byte[] bytes = ModBusCommandUtil.sendReadCommand(serialPort, QUERY_MOTOR_STATUS);
        System.out.println("Arrays.toString(bytes) = " + Arrays.toString(bytes));
        ModBusCommandUtil.sendWriteCommand(serialPort,STOP_MOTOR);
        serialPort.closePort();
    }
}